package dbs

import (
	"github.com/jinzhu/gorm"
	"time"
)

type DbEquipmentDispatch struct {
	ID                uint      `json:"id" gorm:"primary_key"`
	ReviewType        string    `json:"review_type"`      //审批类型 职工  患陪  第三方职工
	OperateType       string    `json:"operate_type"`     //操作类型
	ReviewId          uint      `json:"review_id"`        //审批id
	Status            string    `json:"status"`           //执行状态  未执行  已执行
	Platform          string    `json:"platform"`         //tmesh
	ImplementStatus   string    `json:"implement_status"` //  等待执行   执行成功  执行失败
	ExecutionQuantity uint      `json:"execution_quantity" gorm:"type:tinyint;not null;default:0"`
	Message           string    `json:"message" gorm:"type:text;not null"`
	CreatedAt         time.Time `json:"created_at" gorm:"type:datetime"`
	UpdatedAt         time.Time `json:"updated_at" gorm:"type:datetime"`
}

type EquipmentDispatchList struct {
	ReviewType      string `json:"review_type"`
	ImplementStatus string `json:"implement_status"`
	OperateType     string `json:"operate_type"`
	RecordId        string `json:"record_id"`
	ReviewId        string `json:"review_id"`
	StartAt         string `json:"start_at"`
	EndAt           string `json:"end_at"`
	Status          string `json:"status"`
	Page            int    `json:"page" label:"页数"`
	Limit           int    `json:"limit" label:"每页显示数"`
}

func (self *DbEquipmentDispatch) Create() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		return conn.Create(&self).Error
	})
	return
}

func (self *DbEquipmentDispatch) Get() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if self.Status != "" {
			conn = conn.Where("status = ?", self.Status)
		}

		return conn.Order("id DESC").Find(&self).Error
	})
	return
}

func (self *DbEquipmentDispatch) Update(params map[string]interface{}) (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Model(&self).Update(params).Error
	})
	return
}

func (self *DbEquipmentDispatch) UpdateRaw(db *gorm.DB, params map[string]interface{}) (err error) {
	return db.Model(&self).Update(params).Error
}

func (self *DbEquipmentDispatch) GetList(req EquipmentDispatchList) (data []DbEquipmentDispatch, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		conn = self.listQuery(conn, req)
		// 分页
		if req.Page != 0 && req.Limit != 0 {
			conn = conn.Offset((req.Page - 1) * req.Limit).Limit(req.Limit)
		}
		if req.Status == "已执行" {
			return conn.Model(&self).Order("updated_at DESC").Find(&data).Error
		} else if req.Status == "未执行" {
			return conn.Model(&self).Order("created_at ASC").Find(&data).Error
		}
		return
	})
	return
}

func (self *DbEquipmentDispatch) GetListByName(req EquipmentDispatchList, staffRecord []int, AccRecord []int) (data []DbEquipmentDispatch, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		conn = self.listQuery(conn, req)
		if staffRecord != nil || AccRecord != nil {
			conn = conn.Raw("SELECT * FROM  db_equipment_dispatches WHERE  (review_id IN (?) and review_type ='职工') OR (review_id IN (?) AND review_type ='患陪')", staffRecord, AccRecord)
		}
		// 分页
		if req.Page != 0 && req.Limit != 0 {
			conn = conn.Offset((req.Page - 1) * req.Limit).Limit(req.Limit)
		}
		return conn.Model(&self).Order("id DESC").Find(&data).Error
	})
	return
}

func (self *DbEquipmentDispatch) CountList(req EquipmentDispatchList) (number int, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db
		conn = self.listQuery(conn, req)
		conn = conn.Model(&self).Count(&number)
		err = conn.Error
		return
	})

	return

}

func (self *DbEquipmentDispatch) listQuery(conn *gorm.DB, req EquipmentDispatchList) *gorm.DB {
	if req.ReviewType != "" {
		conn = conn.Where("review_type = ?", req.ReviewType)
	}
	if req.OperateType != "" {
		conn = conn.Where("operate_type = ?", req.OperateType)
	}

	if req.ReviewId != "" {
		conn = conn.Where("review_id like ?", "%"+req.ReviewId+"%")
	}

	if req.Status != "" {
		conn = conn.Where("status = ?", req.Status)
	}
	if req.ImplementStatus != "" {
		conn = conn.Where("implement_status= ?", req.ImplementStatus)
	}
	if req.StartAt != "" {
		conn = conn.Where("created_at >=?", req.StartAt)
	}
	if req.EndAt != "" {
		conn = conn.Where("created_at <=?", req.EndAt)
	}
	return conn
}

func (c *DbEquipmentDispatch) Format() (result map[string]interface{}) {
	//todo last time
	// 格式化用户返回值
	result = map[string]interface{}{
		"id":               c.ID,
		"review_type":      c.ReviewType,
		"operate_type":     c.OperateType,
		"review_id":        c.ReviewId,
		"status":           c.Status,
		"platform":         c.Platform,
		"implement_status": c.ImplementStatus,
		"message":          c.Message,
		"created_at":       c.CreatedAt.Format("2006-01-02 15:04:05"),
		"update_at":        c.UpdatedAt.Format("2006-01-02 15:04:05"),
	}
	return
}
